package com.wjm.blog.core.interceptor;

import com.wjm.blog.common.base.SysUserDetailVo;
import com.wjm.blog.core.annotation.CurrentUser;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

//import com.wjm.blog.core.common.dto.SysUserDetailVo;

/**
 * 从拦截器中, 获取当前登录用户信息, 并注入到接口参数中
 *
 * @author jiyuan
 * @version 1.0
 * @date 2022/03/11
 */
@ConditionalOnExpression("${platform.auth.interceptor.user.enable:true}")
@Component
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {


    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType()
                .isAssignableFrom(SysUserDetailVo.class)
                && methodParameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        // 获取拦截器中获取的当前用户信息
        SysUserDetailVo userDetailVo = (SysUserDetailVo) nativeWebRequest.getAttribute("userDetailVo", RequestAttributes.SCOPE_REQUEST);
        if (userDetailVo != null) {
            return userDetailVo;
        }

        // 如果当前用户信息为null, 则抛出异常
        throw new MissingServletRequestPartException("userDetailVo");
    }

}
